var admin;
if(!admin) {
    admin = {};
}

admin.show_draft = function(){
    var popup = $('.popup_container');
    if(popup.css('display') == "block"){
        $('.popup_container').css('display', 'none');
    } else{
        $('.popup_container').css('display', 'block');
    }
}

admin.set_editor = function(){
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/github");
    editor.getSession().setMode("ace/mode/markdown");
    editor.getSession().setUseWrapMode(true);
    // editor.setShowPrintMargin(true);
    editor.renderer.setShowGutter(true);   // 配合linenumber使用
    // editor.setKeyboardHandler("ace/keyboard/vim");    // ("ace/keyboard/vim");
    editor.setOptions({
        showLineNumbers: true,
        selectionStyle: "text", // "line"|"text"
        highlightActiveLine: false,
        highlightSelectedWord: true,
        cursorStyle: "ace",    // "ace"|"slim"|"smooth"|"wide"
        wrapBehavioursEnabled: true,
        autoScrollEditorIntoView: true
    });
}

admin.setting = function(){
    admin.set_editor_fullscreen();
}

admin.set_editor_fullscreen = function(){
    if(window.is_fullscreen == false){
        $('.editor_container').css('position', 'fixed');
        $('.editor_container').css({
                        'left': '0',
                        'margin': '0',
                        'top': '0',
                        'width': '100%',
                        'height': '100%'
                        });
        $('#editor').css({
            'width': '80%'
        });
        window.is_fullscreen = true;
    } else {
        $('.editor_container').css({
            'margin-top': '100px',
            'height': '80%'
        });
        $('#editor').css({
            'width': '100%'
        });
        $('.editor_container').css('position', 'relative');
        window.is_fullscreen = false;
    }
}

admin.save_blog = function(){
    /*
        blog {
            title: string,
            brief: string,
            is_top: boolean,
            is_share: boolean,
            tags: array,
            category: string,
            content: string,
            draft_id: string(ObjectId)
    */
    var blog = {};
    var res = {};
    blog.title = $('#title').val();
    blog.brief = $('#brief').val();
    blog.html_code = $('#html_code').val();
    blog.is_top = $('#is_top').is(":checked");   // yes=true
    blog.is_share = $('#is_share').is(":checked");
    var tagtext = $('#tags').val();
    blog.tags = tagtext.split(', ');
    blog.category = $("#category").val();
    var editor = ace.edit('editor');
    blog.content = editor.getSession().getValue();
    blog.draft_id = $('#draft_id').text();
    blog.blog_id = $('#blog_id').text();    // 当元素不存在时，返回值为 ''
    // ajax设置为同步，为了之后的一些操作，如：保存退出
    $.ajax({
        async: false,
        type: 'POST',
        url: '/apis/save',
        data: JSON.stringify(blog),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    }).done(function(res_) {
        res = res_;
    });
    // ajax 设置为同步。
    // ajax 可能失败，所以把这段放在ajax外面
    common.notify(res);
    var result = {};
    result.blog = blog;
    result.res = res;
    return result;
}

admin.save_exit = function(){
    var result = admin.save_blog();
    console.log(result);
    var res = result.res;
    if (res.flag == true){
        $(window).unbind("beforeunload");
        window.location.href = '/home'
    } else {
        alert(res.message);
    }
}

admin.publish_blog = function(){
    $(window).unbind("beforeunload");
    var result = admin.save_blog();
    var blog = result.blog;
    common.notify({
        'flag': true,
        'message': '正在上传博客'
    });
    if (blog.title == '' || blog.title == ' '){
        alert('标题不能为空');
    } else {
        $.ajax({
            type: 'POST',
            url: '/apis/publish',
            data: JSON.stringify(blog),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8'
        }).done(function(data) {
            alert(data.message);
            if(data.flag === true){
                window.location.href="/home";
            }
        });
    }
}

admin.delete_draft = function(self){
    var draft_id = $(self).attr('did');
    var data = {};
    var res = {};
    var flag;
    data._id = draft_id;
    var confirm;
    confirm = window.confirm("是否删除草稿？");
    if(confirm != true){
        return false;
    }
    $.ajax({
        async: false,
        type: 'POST',
        url: '/apis/delete/draft/',
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    }).done(function(res_) {
        // 只需要通知即可
        flag = res_.flag;
        res = res_;
    });
    common.notify(res);
    return flag;
}

admin.delete_exit = function(self){
    var flag = admin.delete_draft(self);
    console.log("delete:", flag);
    if (flag == true){
        console.log("jump");
        $(window).unbind("beforeunload");
        window.location.href = '/home';
    } else {
        var jumpornot;
        jumpornot = window.confirm('删除失败，是否仍然跳转到博客主页？');
        if (jumpornot == true){
            $(window).unbind("beforeunload");
            window.location.href = '/home';
        }
    }
}

admin.delete_remove = function(self){
    var flag = admin.delete_draft(self);
    if (flag == true){  // 删除成功
        $(self).parent().remove();
        $('#draft_count').text(parseInt($('#draft_count').text())-1);
    } else {
        alert("删除失败");
    }
}

admin.set_checkbox = function(){
    var is_top = $('#is_top').val();
    var is_share = $("#is_share").val();
    if (is_top == 'True'){
        $("[name='is_top']").attr('checked', 'true');
    }
    if (is_share == 'True'){
        $("[name='is_share']").attr('checked', 'true');
    }
}

admin.set_popup_shortcut = function(){
//    $(document).keydown(function(e){
    $('#popup_draft').keydown(function(e){
        if(e.which == 27){
            $('#popup_draft').css('display', 'none');
            e.preventDefault();
            return false;
        }
        return True;
    });
}

$(document).ready(function(){
    window.is_fullscreen = false;
    admin.set_editor();
    admin.set_checkbox();
    admin.save_blog();
    admin.set_popup_shortcut();
    $(window).bind("beforeunload", function(e){
        return "确定退出该页面?"
    });

    $(window).keypress(function(event) {
        // 注意keypress和keydown的区别
        if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)){
            return true;
        }
        admin.save_blog();
        event.preventDefault();
        return false;
    });
});
